<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-14 10:58:57
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-07-05
-->
<template>
  <RjModal
    width="624px"
    :title="
      voucherForm.uuid
        ? $t('userManage.editVoucher')
        : $t('userManage.addVoucher')
    "
    :visible="isVisible"
    @ok="onOk"
    :confirmLoading="confirmLoading"
    @cancel="onCancel"
  >
    <a-form-model
      :labelCol="{ span: 10 }"
      :wrapperCol="{ span: 14 }"
      labelAlign="left"
      :model="voucherForm"
      ref="voucherFormRef"
      :rules="rules"
      :colon="false"
    >
      <a-form-model-item
        v-if="!voucherForm.uuid"
        class="flex col-top"
        prop="quantity"
        :label="$t('userManage.quantity')"
      >
        <a-input-number
          :disabled="Boolean(voucherForm.uuid)"
          allowClear
          @input="quantityInput"
          v-model="voucherForm.quantity"
        />
      </a-form-model-item>

      <a-form-model-item
        class="flex col-top"
        prop="profile"
        :label="$t('localAccount.authPolicy')"
      >
        <a-select
          :loading="selectLoading"
          @change="change"
          :filterOption="filterOption"
          showSearch
          v-model="voucherForm.profile"
          :options="groupOptions"
        >
          <div slot="dropdownRender" slot-scope="menu">
            <v-nodes :vnodes="menu" />
            <a
              style="padding: 4px 8px 8px; cursor: pointer; display: block"
              @mousedown="(e) => e.preventDefault()"
              @click="onAddAuthPolicy"
            >
              <icon-font type="ic-plus" />
              {{ $t('localAccount.addAuthPlicy2') }}
            </a>
          </div>
        </a-select>
        <div
          style="color: #999"
          v-show="!voucherForm.profile && voucherForm.uuid"
        >
          {{ $t('userManage.oldVoucherUnbindUserGroup') }}
        </div>
      </a-form-model-item>

      <div
        class="expand-item"
        @click="userInfoSetExpanded = !userInfoSetExpanded"
      >
        <span>{{ $t('userManage.userInfoSet') }}</span>
        <icon-font :type="userInfoSetExpanded ? 'ic-up' : 'ic-down'" />
      </div>

      <div v-if="userInfoSetExpanded">
        <a-form-model-item
          class="flex col-top"
          prop="firstName"
          :label="$t('userManage.firstName')"
        >
          <a-input allowClear v-model="voucherForm.firstName" />
        </a-form-model-item>

        <a-form-model-item
          class="flex col-top"
          prop="lastName"
          :label="$t('userManage.lastName')"
        >
          <a-input allowClear v-model="voucherForm.lastName" />
        </a-form-model-item>

        <a-form-model-item
          class="flex col-top"
          :label="$t('userManage.email')"
          prop="email"
        >
          <a-input allowClear v-model="voucherForm.email" />
        </a-form-model-item>

        <a-form-model-item
          class="flex col-top"
          prop="phone"
          :label="$t('userManage.phone')"
        >
          <a-input allowClear v-model="voucherForm.phone" />
        </a-form-model-item>
        <a-form-model-item
          class="flex col-top"
          prop="comment"
          :label="$t('userManage.alias')"
        >
          <a-input allowClear v-model="voucherForm.comment" />
        </a-form-model-item>
      </div>

      <div v-show="!voucherForm.uuid">
        <div
          class="expand-item"
          @click="advanceSetExpanded = !advanceSetExpanded"
        >
          <span>{{ $t('userManage.advanceSetting') }}</span>
          <icon-font :type="advanceSetExpanded ? 'ic-up' : 'ic-down'" />
        </div>
        <a-form-model-item
          v-if="advanceSetExpanded"
          class="flex col-top"
          :label="$t('userManage.voucherCodeType')"
          prop="createCodeType"
        >
          <a-select
            v-model="voucherForm.createCodeType"
            defaultValue="1"
            :disabled="Boolean(voucherForm.uuid)"
          >
            <a-select-option value="1">{{
              $t('userManage.alphanumeric')
            }}</a-select-option>
            <a-select-option value="2">{{
              $t('userManage.alphabetic')
            }}</a-select-option>
            <a-select-option value="3">{{
              $t('userManage.numeric')
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          class="flex col-top"
          prop="codeSize"
          v-if="advanceSetExpanded"
          :label="$t('userManage.voucherLength')"
        >
          <a-select v-model="voucherForm.codeSize">
            <a-select-option
              :value="item"
              v-for="item in [6, 7, 8, 9]"
              :key="item"
              >{{ item }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </div>
    </a-form-model>
  </RjModal>
</template>

<script>
import { requestHttp, maccApi } from '@utils/index';
import { mapState } from 'vuex';
import { getByteLength } from '@/utils';
import { ValiDateTools } from '@/utils';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import lodash from 'lodash';
export default {
  name: 'addAuthVoucherModal',
  mixins: [authSysMixin],
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  // model: {
  //   prop: 'value',
  //   event: 'set',
  // },
  // props: {
  //   value: Boolean,
  // },
  data() {
    const checkQuantity = (rule, val, cb) => {
      val = Number(val);
      if (val < 1 || val > 500 || Number.isNaN(val)) {
        cb(new Error(this.$t('userManage.quantityTip')));
      } else {
        cb();
      }
    };
    const checkEmail = (rule, val, cb) => {
      let length = getByteLength(val);
      if (val && length > 64) {
        cb(new Error(this.$t('userManage.commentLengthTip')));
      } else if (val && !ValiDateTools.emailRegex.test(val)) {
        cb(new Error(this.$t('userManage.enterCorrectEmail')));
      } else {
        cb();
      }
    };
    const checkPhone = (rule, val, cb) => {
      if (val) {
        if (getByteLength(val) > 25) {
          cb(new Error(this.$t('userManage.phoneLengthTip')));
        } else if (!ValiDateTools.numericRegex.test(val)) {
          cb(new Error(this.$t('userManage.phoneNumberTip')));
        } else {
          cb();
        }
      } else {
        cb();
      }
    };

    const checkName = (rule, val, cb) => {
      if (val) {
        if (getByteLength(val) > 60) {
          cb(new Error(this.$t('userManage.nameLengthTip')));
        } else if (!ValiDateTools.alphaNumericUnderscoreRegex.test(val)) {
          cb(new Error(this.$t('userManage.enterNumbersLettersUnderscores')));
        } else {
          cb();
        }
      } else {
        cb();
      }
    };

    const checkComment = (rule, val, cb) => {
      if (val) {
        if (getByteLength(val) > 64) {
          cb(new Error(this.$t('userManage.commentLengthTip')));
        } else if (!ValiDateTools.alphaNumericUnderscoreBlankRegex.test(val)) {
          cb(new Error(this.$t('userManage.enterNumbersLettersUnderscores')));
        } else {
          cb();
        }
      } else {
        cb();
      }
    };
    const rules = {
      quantity: [
        {
          required: true,
          trigger: 'blur',
          message: this.$t('userManage.fieldIsRquired'),
        },
        {
          required: true,
          validator: checkQuantity,
          trigger: ['change', 'blur'],
        },
      ],
      profile: [
        {
          required: true,
          trigger: 'change',
          message: this.$t('userManage.fieldIsRquired'),
        },
      ],
      email: [
        {
          trigger: ['change', 'blur'],
          validator: checkEmail,
        },
      ],
      phone: [
        {
          trigger: ['change', 'blur'],
          validator: checkPhone,
        },
      ],
      firstName: [
        {
          trigger: ['change', 'blur'],
          validator: checkName,
        },
      ],
      lastName: [
        {
          trigger: ['change', 'blur'],
          validator: checkName,
        },
      ],
      comment: [
        {
          trigger: ['change', 'blur'],
          validator: checkComment,
        },
      ],
    };
    return {
      userInfoSetExpanded: false,
      advanceSetExpanded: false,
      rules,
      voucherForm: {
        createCodeType: '1',
        codeSize: 6,
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        comment: '',
      },
      confirmLoading: false,
      selectLoading: false,
      addModalShow: false,
      isVisible: false,
    };
  },
  watch: {
    value(val) {
      // val && this.getGroup();
    },
  },
  computed: {
    ...mapState('AuthCommon', ['authPolicys']),

    groupOptions() {
      return this.authPolicys.map(
        (item) =>
          (item = {
            ...item,
            ...{ label: item.name, value: item.uuid },
          })
      );
    },
  },
  methods: {
    setAuthPolicyId(policyId) {
      this.voucherForm.profile = policyId;
    },
    onAddAuthPolicy() {
      this.$emit('addAuthPolicy');
    },
    openModal(record) {
      this.isVisible = true;
      if (record) {
        this.voucherForm = lodash.cloneDeep(record);
        this.$set(this.voucherForm, 'profile', this.voucherForm.userGroupId);
      }
    },
    quantityInput(e) {
      let { value } = e.target;
      this.voucherForm.quantity = value.replace(/\D/g, '');
    },
    onOk() {
      this.$refs.voucherFormRef.validate((valid) => {
        if (valid) {
          if (this.voucherForm.uuid) {
            this.edit();
          } else {
            this.add();
          }
        }
      });
    },
    change(e) {
      if (e == 'custom') {
        this.voucherForm.profile = '';
        this.addModalShow = true;
      }
    },
    async edit() {
      let querys = {
        tenantId: this.tenantInfo.tenantId,
        groupId: this.groupId,
        group_id: this.groupId,
      };
      let params = { ...this.voucherForm };
      params.userGroupId = params.profile;
      params.groupId = this.groupId;
      params.profileId = params.profile;
      this.confirmLoading = true;
      let res = await this.requestHttpAuth({
        api: maccApi.MACC_VOUCHER_UPDATE_POST_API,
        method: 'POST',
        querys,
        params,
      });
      this.confirmLoading = false;
      if (!res.data.code) {
        this.$message.success(this.$t('common.editSuccess'));
        this.onCancel();
        this.$emit('refreshList');
      } else {
        this.$message.warning(res.data.msg);
      }
    },
    afterClose() {
      this.voucherForm = {
        createCodeType: '1',
        codeSize: 6,
        firstName: '',
        lastName: '',
        email: '',
        phone: '',
        comment: '',
      };
    },
    async add() {
      let replaces = {
        tenantName: encodeURI(this.tenantInfo.tenantName),
        userName: encodeURI(this.userInfo.account).trim(),
        groupId: this.groupId,
      };
      let querys = {
        tenantId: this.tenantInfo.tenantId,
      };
      let params = { ...this.voucherForm };
      params.userGroupId = params.profile;
      this.confirmLoading = true;

      let res = await this.requestHttpAuth({
        api: maccApi.MACC_VOUCHER_ADD_POST_API,
        method: 'POST',
        replaces,
        querys,
        params,
      });

      this.confirmLoading = false;
      if (!res.data.code) {
        this.$message.success(this.$t('common.addSuceess'));
        this.onCancel();
        this.$emit('refreshList');
      } else {
        this.$message.warning(res.data.msg);
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    onCancel() {
      for (let key in this.voucherForm) {
        this.voucherForm[key] = '';
      }
      this.isVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.ant-form-item {
  margin-bottom: 8px;
}
.expand-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #000000e5;
  cursor: pointer;
  margin-bottom: 16px;
  font-weight: 500;
  i {
    margin-top: 3px;
    font-size: 18px;
  }
}
.flex {
  display: flex !important;
  flex-direction: row !important;
  align-items: center;
}
.col-top {
  align-items: flex-start !important;
}
.mb-16 {
  margin-bottom: 16px;
}
.ant-input-number {
  width: 100%;
}
</style>
